package com.mqtt.ctwingmqtt.controller;

import com.mqtt.ctwingmqtt.domain.ResponseResult;
import com.mqtt.ctwingmqtt.domain.entity.NIIEntity;
import com.mqtt.ctwingmqtt.service.IIService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/NII")
public class NIIController {
    @Autowired
    private IIService iIService;
    //添加imei 设备id 设备地址（名称）
    @PostMapping("/addfile")
    public ResponseResult<String> add(MultipartFile file){
        //传入一个excel文件读取文件的前三列作为设备信息 imei 设备id 设备地址（编号）
        //定义返回的结果
        //成功的个数
        int i = 0;
        //失败的设备地址列表
        List<String> errors = new ArrayList<>();
        try {
            //读取文件
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            //遍历行，跳过第一行的表头
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if(row == null)continue;

                // 读取前三列：imei, 设备id, 设备地址（编号）
                String imei = getCellValue(row.getCell(0)); // 第一列
                String deviceId = getCellValue(row.getCell(1)); // 第二列
                String deviceAddress = getCellValue(row.getCell(2)); // 第三列


                NIIEntity niiEntity = new NIIEntity();
                niiEntity.setImei(imei);
                niiEntity.setDeviceid(deviceId);
                niiEntity.setDeviceaddress(deviceAddress);
                try {
                    Boolean result = iIService.add(niiEntity);
                    if(result){
                        i++;
                    }else errors.add(deviceAddress);
                } catch (Exception e) {
                    errors.add(deviceAddress);
                }

            }
            //关闭工作簿
            workbook.close();

        }catch (Exception e){
            return ResponseResult.error("文件读取失败");
        }
        return ResponseResult.successs(i,errors);
    }
    // 辅助方法：获取单元格的值并转换为字符串
    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                // 使用 DataFormatter 将数值转换为原始字符串
                DataFormatter dataFormatter = new DataFormatter();
                return dataFormatter.formatCellValue(cell);
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }


    // 单个添加设备信息
    @PostMapping("/addSingle")
    public ResponseResult<String> addSingle(@RequestBody NIIEntity niiEntity) {
        try {
            Boolean result = iIService.add(niiEntity);
            if (result) {
                return ResponseResult.success("设备关联成功");
            } else {
                return ResponseResult.error("设备关联失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("设备关联失败: " + e.getMessage());
        }
    }
}
